import prompt from '@ohos.prompt';
import deviceManager from '@ohos.distributedHardware.deviceManager';

const TAG: string = 'BtConnector[RemoteDeviceModel]'

let SUBSCRIBE_ID = 100;

export default class RemoteDeviceModel {
public tmpCounter = 0
    deviceList = [];
    discoverList = [];
    callback;
    authCallback;
    deviceManager = undefined;

    registerDeviceListCallback(callback) {
        console.info(`${TAG} registerDeviceListCallback`);
        if (typeof (this.deviceManager) === 'undefined') {
            console.log(`${TAG} deviceManager.createDeviceManager begin`);
            deviceManager.createDeviceManager("ohos.samples.distributedcalc", (error, value) => {
                if (error) {
                    console.error(`${TAG} createDeviceManager failed.`);
                    return;
                }
                this.deviceManager = value;
                this.registerDeviceListCallback_(callback);
                console.log(`${TAG} createDeviceManager callback returned, error=` + error + " value=" + value);
            });
            console.log(`${TAG} deviceManager.createDeviceManager end`);
        } else {
            this.registerDeviceListCallback_(callback);
        }
    }

    registerDeviceListCallback_(callback) {
        console.info(`${TAG} registerDeviceListCallback_`);
        this.callback = callback;
        if (this.deviceManager === undefined) {
            console.error(`${TAG} deviceManager has not initialized`);
            this.callback();
            return;
        }

        console.info(`${TAG} getTrustedDeviceListSync begin`);
        let list = this.deviceManager.getTrustedDeviceListSync();
        console.log(`${TAG} getTrustedDeviceListSync end, deviceList=` + JSON.stringify(list));
        if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') {
            this.deviceList = list;
        }
        this.callback();
        console.info(`${TAG} callback finished`);

        this.deviceManager.on('deviceStateChange', (data) => {
            console.log(`${TAG} deviceStateChange data=` + JSON.stringify(data));
            switch (data.action) {
                case deviceManager.DeviceStateChangeAction.READY:
                    this.discoverList = []
                    this.deviceList.push(data.device)
                    console.log(`${TAG} ready, updated device list=` + JSON.stringify(this.deviceList));
                    let list = this.deviceManager.getTrustedDeviceListSync();
                    console.log(`${TAG} getTrustedDeviceListSync end, deviceList=` + JSON.stringify(list));
                    if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') {
                        this.deviceList = list;
                    }
                    this.callback();
                    break;
                case deviceManager.DeviceStateChangeAction.OFFLINE:
                    if (this.deviceList.length > 0) {
                        let list = [];
                        for (let j = 0; j < this.deviceList.length; j++) {
                            if (this.deviceList[j].deviceId !== data.device.deviceId) {
                                list[j] = data.device;
                            }
                        }
                        this.deviceList = list;
                    }
                    console.log(`${TAG} offline, updated device list=` + JSON.stringify(data.device));
                    this.callback();
                    break;
                default:
                    break;
            }
        });
        this.deviceManager.on('deviceFound', (data) => {
            console.log(`${TAG} deviceFound data=` + JSON.stringify(data));
            console.log(`${TAG} deviceFound this.discoverList=` + this.discoverList);
            for (let i = 0;i < this.discoverList.length; i++) {
                if (this.discoverList[i].deviceId === data.device.deviceId) {
                    console.info(`${TAG} device founded ignored`);
                    return;
                }
            }
            this.discoverList[this.discoverList.length] = data.device;
            console.log(`${TAG} deviceFound this.discoverList=` + this.discoverList);
            this.callback();
        });
        this.deviceManager.on('discoverFail', (data) => {
this.tmpCounter++
            prompt.showToast({
                message: 'discoverFail reason=' + data.reason,
                duration: 3000,
            });
            console.log(`${TAG} discoverFail data=` + JSON.stringify(data));
        });
        this.deviceManager.on('serviceDie', () => {
            prompt.showToast({
                message: 'serviceDie',
                duration: 3000,
            });
            console.error(`${TAG} serviceDie`);
        });

        SUBSCRIBE_ID = Math.floor(65536 * Math.random());
        let info = {
            subscribeId: SUBSCRIBE_ID,
            mode: 0xAA,
            medium: 2,
            freq: 2,
            isSameAccount: false,
            isWakeRemote: true,
            capability: 0
        };
        console.log(`${TAG} startDeviceDiscovery ` + SUBSCRIBE_ID);
        this.deviceManager.startDeviceDiscovery(info);
    }

    unregisterDeviceListCallback() {
        console.log(`${TAG} stopDeviceDiscovery ` + SUBSCRIBE_ID);
        if (this.deviceManager === undefined) {
            return
        }
        this.deviceManager.stopDeviceDiscovery(SUBSCRIBE_ID);
        this.deviceManager.off('deviceStateChange');
        this.deviceManager.off('deviceFound');
        this.deviceManager.off('discoverFail');
        this.deviceManager.off('serviceDie');
        this.deviceList = [];
    }

    authenticateDevice(device, callBack) {
        console.log(`${TAG} authenticateDevice ` + JSON.stringify(device));
        for (let i = 0; i < this.discoverList.length; i++) {
            if (this.discoverList[i].deviceId === device.deviceId) {
                let extraInfo = {
                    'targetPkgName': 'ohos.samples.distributedcalc',
                    'appName': 'Distributed Calc',
                    'appDescription': 'Distributed Calc',
                    'business': '0'
                };
                let authParam = {
                    'authType': 1,
                    'extraInfo': extraInfo
                };
                if (this.deviceManager === undefined) {
                    return
                }
                this.deviceManager.authenticateDevice(device, authParam, (err, data) => {
                    if (err) {
                        console.error(`${TAG} authenticateDevice error:` + JSON.stringify(err));
                        this.authCallback = null;
                        return;
                    }
                    console.log(`${TAG} authenticateDevice succeed:` + JSON.stringify(data));
                    this.authCallback = callBack;
                    this.authCallback()
                })
            }
        }
    }
}
